package chapter04;

public class Java16_Object_Recursion {
    public static void main(String[] args) {
        // TODO 递归
        // 方法调用自身，称之为递归方法
        /*
            1.递归方法应该具备跳出逻辑：java.lang.StackOverflowError
            2.调用自身时传递的参数需要具备规律
         */

        /*
            求20以内的奇数和
            1+3+5+7+9+11+13+15+17+19
            计算是有边界的
         */
        int result = computeAP(10);
        System.out.println(result);

        System.out.println("===========================");

        /*
            阶乘：5! => (4,3,2,1) => 5*4*4*3*2*1
            0的阶乘为1
            一个大于1的数的阶乘等于这个数-1的阶乘
         */
        int result2 = computeFactorial(5);
        // int result2 = computeFactorial(50000); 报错：java.lang.StackOverflowError
        System.out.println(result2);

    }

    public static int computeAP(int num) {
        num = num % 2 == 0 ? num - 1 : num;
        if (num == 1) {
            return 1;
        } else {
            return num + computeAP(num - 2);
        }
    }

    public static int computeFactorial(int num) {
        if (num <= 1) {
            return 1;
        } else {
            return num + computeFactorial(num - 1);
        }
    }
}
